﻿using System.Threading;

namespace IQIGame.Onigao.GamePlay
{
    public class DeadViewComponent : TComponent
    {
        private const int deadAnimeDuration = 2000;
        public UnitView unit { get; private set; }

        public bool realDead = false;
        private CancellationTokenSource _cancel;

        protected override void OnDispose()
        {
            if (this._cancel != null)
            {
                this._cancel.Cancel();
                this._cancel = null;
            }
            var rView = this.unit.GetComponent<UnitViewComponent>(ETComponentType.UnitViewComponent);
            rView?.Relive();
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as UnitView;

            var rView = this.unit.GetComponent<UnitViewComponent>(ETComponentType.UnitViewComponent);
            rView.Die();
            this._cancel = new CancellationTokenSource();
            BattleClientUtil.DelayInvoke(deadAnimeDuration, this.RealDead, this._cancel.Token).Forget();
        }

        private void RealDead()
        {
            this.realDead = true;
            if (!this.unit.disposed)
            {
                var rViewComp = this.unit.GetComponent<UnitViewComponent>(ETComponentType.UnitViewComponent);
                rViewComp.enabled = false;
            }
            this._cancel = null;
        }
    }
}